import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:pdf/pdf.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
// import 'package:photo_scan/languages.dart';
import 'package:share/share.dart';
import 'package:path/path.dart' as path;
import 'CountryPage.dart';
import 'TextPage.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'languages.dart';

// import 'package:platform/platform.dart';
// import 'package:dio/';
//      https://api.ocr.space/Parse/Image"
// FormData formData = FormData.fromMap({
//       "apikey": OCR_API_KEY,
//       "file": await MultipartFile.fromFile(image),
//       "language": language
//     });
class SharePage extends StatefulWidget {
  PickedFile data;

  SharePage(this.data);

  @override
  _SharePageState createState() => _SharePageState();
}

class _SharePageState extends State<SharePage> {
  PickedFile resultFile;
  String src;
  String OCR_API_KEY = "230c9e7e6088957";
  String OCR_API_URL = "https://api.ocr.space/Parse/Image";

  share() async {
    final pdf = pw.Document();
    var image = pw.MemoryImage(File(widget.data.path).readAsBytesSync());
    pdf.addPage(pw.Page(
        build: (pw.Context context) => pw.Center(child: pw.Image(image))));
    final output = await getTemporaryDirectory();
    File file =
        File("${output.path}/${DateTime.now().microsecondsSinceEpoch}.pdf");
    await file.writeAsBytes(await pdf.save());
    // log(file.path);
    Share.shareFiles([file.path]);
    resultFile = widget.data;
  }

  transit() async {
    // log("${widget.data.path}");
    // return;
    showCupertinoDialog(context: context, builder: (context)=>Material(
      type: MaterialType.transparency,
      child: Center(
        child: GestureDetector(
          onTap: (){
            Navigator.pop(context);
            return;
          },
          child: Container(
              width: 100,
              height: 70,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color: Colors.white
              ),
              child: CupertinoActivityIndicator()),
        ),
      ),
    ));
    String lan = getLanguage(src);
    Directory dir = await getTemporaryDirectory();
    String name = widget.data.path.split('.').last;
    await FlutterImageCompress.compressWithFile(widget.data.path,
            inSampleSize: 3)
        .then((value) async {
      File file = File("${dir.path}/${DateTime.now().millisecond}.$name");
      await file.writeAsBytesSync(value);
      log("压缩后的长度:${file.lengthSync()}");
      FormData formData = FormData.fromMap({
        "apikey": OCR_API_KEY,
        "file": await MultipartFile.fromFile(file.path),
        "language": lan,
        // "OCREngine":2
      });
      Dio dio = Dio();
      dio.options.connectTimeout = 5000;
      Response response;
      try {
        response = await dio.post(
          OCR_API_URL,
          data: formData,
        );
      } catch (e) {
        Navigator.pop(context);
        Fluttertoast.showToast(msg: "Check your Internet");
        return;
      }
      if (response.statusCode == 200) {
        var result = jsonDecode(response.toString());
        // log(result.toString());
        List<String> list = [];
        // log(result['ParsedResults'].length.toString());
        for (String line
            in result['ParsedResults'][0]['ParsedText'].split('\r\n')) {
          list.add(line.trim());
        }
        // for(var item in result["ParsedResults"]) {
        //   // text += item["ParsedText"];
        //   //   list.add(item["ParsedText"]);
        //   log(item.toString());
        // }return;
        if (list.isNotEmpty) {
          resultFile = widget.data;
          Navigator.pop(context, resultFile);
          Navigator.push(
              context, MaterialPageRoute(builder: (_) => TextPage(list)));
        } else {
          Fluttertoast.showToast(msg: "Please retry!");
        }
      } else {
        Fluttertoast.showToast(msg: "Please check your Internet");
      }
    });
    // Navigator.pop(context);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    src = "English";
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffeeeeee),
      appBar: AppBar(
        brightness: Brightness.light,
        backgroundColor: Colors.transparent,
        title: Text(
          "Simple Share",
          style: TextStyle(color: Colors.black),
        ),
        centerTitle: true,
        elevation: 0,
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context, resultFile);
          },
          child: Icon(
            Icons.arrow_back_ios_rounded,
            size: 20,
            color: Colors.black,
          ),
        ),
        actions: [
          IconButton(
              icon: Icon(
                Icons.ios_share,
                color: Colors.black,
              ),
              onPressed: share)
        ],
      ),
      body: WillPopScope(
        onWillPop: ()async{
          Navigator.pop(context,resultFile);
          return true;
        },
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(top: 20, bottom: 30, left: 16, right: 16),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: Colors.white, width: 6)),
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: Image.file(
                      File(widget.data.path),
                      width: MediaQuery.of(context).size.width * 0.9,
                    )),
              ),
            ),

          ],
        ),
      ),
      floatingActionButton: Container(
        margin: EdgeInsets.only(right: 16),
        child: Row(
          // mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(flex:5,child: SizedBox()),
            GestureDetector(
              onTap: () {
                showModalBottomSheet(
                    context: context,
                    builder: (context) => CountryPage()).then((value) {
                  if (value != null) {
                    src = value;
                    setState(() {});
                  }
                });
                // Navigator.push(context, MaterialPageRoute(builder: (_)=>CountryPage())).then((value){
                //   if(value !=null){
                //
                //   }
                // });
              },
              child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                  decoration: BoxDecoration(
                    color: Color(0xff4474fb),
                    borderRadius: BorderRadius.circular(50),
                  ),
                  child: Row(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(50),
                        child: Image.asset(
                          "images/$src.png",
                          width: 30,
                          height: 30,
                          fit: BoxFit.cover,
                        ),
                      ),
                      SizedBox(width: 10),
                      Text(
                        "$src",
                        style: TextStyle(
                            fontWeight: FontWeight.w500, color: Colors.white),
                      ),
                      Icon(
                        Icons.navigate_next_rounded,
                        color: Colors.white,
                      )
                    ],
                  )),
            ),
            Expanded(flex:2,child: SizedBox()),
            GestureDetector(
              onTap: transit,
              child: Container(
                  padding: EdgeInsets.all(15),
                  decoration: BoxDecoration(
                      color: Color(0xff4474fb),
                      borderRadius: BorderRadius.circular(50)
                  ),
                  child: Icon(Icons.g_translate_rounded,color: Colors.white,)),
            ),
          ],
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }
}
